#pragma once

#include "d3dbase.h"
#include "d3dmath.h"

class AnimatedMesh {
	enum {
		FVF_ANIMATEDMESH = (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_NORMAL | D3DFVF_TEX1)
	};
	struct AnimatedMeshVertex
	{
		D3DMath::Vec3 pos;
		D3DMath::Vec3 normal;
		unsigned int color;
		float u,v;
		//float u2,v2;
	};

	AnimatedMeshVertex *origVerts;
	AnimatedMeshVertex *verts;
	int numVerts;
	int *bone;

	//Skeleton *skeleton;

	int numInds;

	unsigned short *inds;
	LPDIRECT3DVERTEXBUFFER9 vb;
	LPDIRECT3DINDEXBUFFER9 ib;

	bool loaded;
public:
	unsigned int outlineColor;
	AnimatedMesh();
	virtual ~AnimatedMesh();

	void allocVerts(int numv);
	void allocInds(int numi);
	//void setSkeleton(Skeleton *skel) {skeleton=skel;}
	void reset() {
		if (!verts) 
			return;
		memcpy(verts, origVerts, sizeof(AnimatedMeshVertex)*numVerts);
	}
	void uploadVerts() {
		AnimatedMeshVertex *v = lockVB();
		memcpy(v, verts, sizeof(AnimatedMeshVertex)*numVerts);
		unlockVB();
	}
	void uploadInds() {
		unsigned short *i = lockIB();
		memcpy(i, inds, sizeof(unsigned short)*numInds);
		unlockIB();
	}
	void upload() {
		uploadVerts();
		uploadInds();
	}
	void destroy();
	//void applyBones();
	int read(unsigned char *data);
	AnimatedMeshVertex *lockVB();
	void unlockVB() { vb->Unlock(); }
	unsigned short *lockIB();

	void unlockIB() { ib->Unlock(); }
	void draw(bool nocull=false);
	void drawPts();
	void calcNormals();
	void smooth(float threshold = 3.0f); //hack :D

	void generateFlatMeshIndices(unsigned short *inds, int base, int xsections, int ysections, bool stitchx=false, bool stitchy=false);
	void generatePlaneVerts(AnimatedMeshVertex *verts, int xsections, int zsections, float yoff, unsigned int *heightMap, D3DMath::Matrix4x4 *rotator, bool round=false);
	void generateDiscIndices(unsigned short *inds, int base, int numSides);
	void generateDiscVerts(AnimatedMeshVertex *verts, int numsides, float yoff, bool flip);

	void generatePlane(int xsections, int zsections, unsigned int *heightMap);
	void generateCube(int xsections, int ysections, int zsections);
	void generateSphere(int xsections);
	void generateCylinder(int xsections, int zsections, bool capped);
	void generateTorus(int xsections, int zsections, float radius);

	void distort(float time);
	void distortcarrion(float time);
	void uvMap(int type, float mul1, float mul2, float mul3=0.0f);
	void mulUV(float mulU,float mulV);
	void weld();
	void skojTwist(float time);
	void skojTunnel(float time, D3DMath::Vec3 &camPos, D3DMath::Vec3 &camDir, int xsegs, int ysegs, float sync);
	void colorFadeY(float mul);
};


